﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace ShortLink.Common.Redis
{
    public class RedisAccessor : IRedisAccessor
    {
        private readonly IDatabase _database;

        public RedisAccessor(IConnectionMultiplexer redis)
        {
            _database = redis.GetDatabase();
        }
        // 设置值
        public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null)
        {
            string jsonData = JsonSerializer.Serialize(value);
            await _database.StringSetAsync(key, jsonData, expiry);
        }

        // 获取值
        public async Task<T?> GetAsync<T>(string key)
        {
            string? jsonData = await _database.StringGetAsync(key);
            return jsonData is not null ? JsonSerializer.Deserialize<T>(jsonData) : default;
        }

        // 删除值
        public async Task<bool> RemoveAsync(string key)
        {
            return await _database.KeyDeleteAsync(key);
        }
    }
}
